import { UserActions } from '@/reducers/user';
import store from '@/store';
import { getToken } from '@/utils/index';
import { message } from 'antd';
import Axios from 'axios';

const request = Axios.create({
  baseURL: process.env.BASE_URL,
  headers: { 'content-type': 'application/json' },
});

export const CODES = {
  SUCCESS: ['000', '111'],
  EXPIRED: '007',
  ESERVER: '-1',
  ENETWORK: '-2',
};

const duration = 5;

request.interceptors.request.use((config) => ({
  ...config,
  headers: {
    ...(config?.headers ?? null),
    token: getToken(),
  },
}));

request.interceptors.response.use(
  (response) => {
    const { data, config, status } = response;

    console.log(`res ${config.url} ${config.method}`, data.code);

    if (!data) {
      message.error('服务器返回为空', duration);
      return Promise.reject({ code: CODES.ESERVER, data: null, msg: '服务器返回为空', status });
    }

    if (data.code === CODES.EXPIRED) {
      store.dispatch(UserActions.logout());
    }

    if (!CODES.SUCCESS.includes(data.code)) {
      if (config.url === '/UploadAttachmentController/uploadFiles' && data.code === '100') return data;
      if (!config.hideMsg) message.error(data.msg, duration);
      if (!config.dontThrow) return Promise.reject(data);
    }

    return data;
  },
  (error) => {
    if (Axios.isCancel(error)) return Promise.reject(error);
    const { response } = error;

    if (response?.data) {
      return Promise.reject(response.data);
    }

    return Promise.reject({ code: CODES.ENETWORK, data: null, msg: '网络异常', response });
  },
);

export default request;
